package com.lehezn.opensource.appkit.ControlModule;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.lehezn.opensource.appkit.R;

import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by es-ll on 17/10/20.
 */

public class EditEleActivity extends GosControlModuleBaseActivity {
    private TextView tvMonthEle, tvDayEle, tvCurrentEle, tvJianEle, tvPingEle, tvFengEle, tvGuEle, tvV, tvCur, tvPower, tvFactory, tvAddr,tvAllPrice;
    private Button btn7Day, btn31Day, btn12Month, btnRefresh;
    private LineChart lineChart;
    public static MeterInfo meterInfo;
    public View lyContent;
    public SwipeRefreshLayout swipeRefreshLayout;
    double priceOfJian,priceOfFeng,priceOfPing,priceOfGu,priceOfWater,priceOfGos,priceOfHeater;

    private enum CurrentClick {
        days_7, days_30, month_12
    }

    private CurrentClick currentClick = CurrentClick.days_7;
    int labelSize = 7;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_a_edit_e_2);
        initDevice();
        initPrice();
        initView();
        setActionBar(true, true, meterInfo.name == null ? "表信息" : meterInfo.name);
        updateUi();
        addListener();
    }

    private void initPrice() {
        try {


            priceOfJian = Double.parseDouble(spf.getString(Util.PRICE_JIAN, "0.3"));
            priceOfFeng = Double.parseDouble(spf.getString(Util.PRICE_FENG, "0.4"));
            priceOfPing = Double.parseDouble(spf.getString(Util.PRICE_PING, "0.5"));
            priceOfGu = Double.parseDouble(spf.getString(Util.PRICE_GU, "0.2"));
            priceOfWater = Double.parseDouble(spf.getString(Util.PRICE_WATER, "0.5"));
            priceOfGos = Double.parseDouble(spf.getString(Util.PRICE_GOS, "0.5"));
            priceOfHeater = Double.parseDouble(spf.getString(Util.PRICE_HEART, "0.5"));
        }catch (Exception e){
            e.printStackTrace();
        }


    }


    /*
        * ========================================================================
        * 菜单栏
        * ========================================================================
        */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.shareddevice, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case R.id.showhelppage:

                Intent intent = new Intent(this, AddEleActivity.class);
                AddEleActivity.meterInfo = meterInfo;
                Bundle bundle = new Bundle();
                bundle.putParcelable("GizWifiDevice", device);
                intent.putExtras(bundle);
                intent.putExtra("action", Util.ACTION_MODIFY);
                startActivity(intent);

                break;

            default:
                break;
        }

        return super.onOptionsItemSelected(item);
    }


    private void initView() {
        tvAllPrice= (TextView) findViewById(R.id.tv_all_price);
        tvMonthEle = (TextView) findViewById(R.id.tv_edit_month);
        tvDayEle = (TextView) findViewById(R.id.tv_edit_day);
        tvCurrentEle = (TextView) findViewById(R.id.tv_edit_current_e);
        tvJianEle = (TextView) findViewById(R.id.tv_jian_e);
        tvPingEle = (TextView) findViewById(R.id.tv_ping_e);
        tvFengEle = (TextView) findViewById(R.id.tv_feng_e);
        tvGuEle = (TextView) findViewById(R.id.tv_gu_e);
        tvV = (TextView) findViewById(R.id.tv_v);
        tvCur = (TextView) findViewById(R.id.tv_current);
        tvPower = (TextView) findViewById(R.id.tv_power);
        tvFactory = (TextView) findViewById(R.id.tv_yinshu);

        tvAddr = (TextView) findViewById(R.id.tv_addr);

        btn7Day = (Button) findViewById(R.id.button_7day);
        btn31Day = (Button) findViewById(R.id.button_31day);
        btn12Month = (Button) findViewById(R.id.button_12month);

        lineChart = (LineChart) findViewById(R.id.chart);
        initChart();

        lyContent = findViewById(R.id.ly_content);

        btnRefresh = (Button) findViewById(R.id.button_refresh);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.button_refresh1);
        swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.yellow));

    }


    private void initDevice() {
        Intent intent = getIntent();

        device = (GizWifiDevice) intent.getParcelableExtra("GizWifiDevice");
        device.setListener(gizWifiDeviceListener);

//        meterInfo =meterInfo (MeterInfo) intent.getParcelableExtra("MeterInfo");
    }

    private String getElePrice(){
        return ComputeUtil.add(ComputeUtil.mul(priceOfJian,meterInfo.enery0),
                ComputeUtil.mul(priceOfFeng,meterInfo.enery1),
                ComputeUtil.mul(priceOfPing,meterInfo.enery2),
                ComputeUtil.mul(priceOfGu,meterInfo.enery3))+"";

    }

    private String getWaterPrice(){
        return ""+ComputeUtil.mul(priceOfWater,meterInfo.enery);
    }
 private String getGosPrice(){
        return ""+ComputeUtil.mul(priceOfGos,meterInfo.enery);
    }
 private String getHeaterPrice(){
        return ""+ComputeUtil.mul(priceOfHeater,meterInfo.enery);
    }

    private void updateUi() {

        if (meterInfo.type == Util.TYPE_WATER || meterInfo.type == Util.TYPE_GOS
                || meterInfo.type == Util.TYPE_HEAT) {

            lyContent.setVisibility(View.GONE);
            tvAddr.setText(meterInfo.addrStr.replace(" ", ""));
            tvAllPrice.setText(getWaterPrice()+"元");
            btn7Day.setText("7日水量");
            btn31Day.setText("31日水量");
            btn12Month.setText("12月水量");
            tvCurrentEle.setText(meterInfo.enery + "吨");

        } else {
            tvAddr.setText(meterInfo.addrStr.replace(" ", ""));
            tvAllPrice.setText(getElePrice()+"元");
            tvCurrentEle.setText(meterInfo.enery + "度");

        }

//        tvMonthEle.setText(meterInfo.getCurMonthEnery() + "");
//        tvDayEle.setText(meterInfo.getCurDayEnery() + "");
        tvJianEle.setText(meterInfo.enery0 + "度");
        tvPingEle.setText(meterInfo.enery2 + "度");
        tvFengEle.setText(meterInfo.enery1 + "度");
        tvGuEle.setText(meterInfo.enery3 + "度");
        tvV.setText(meterInfo.vol + "V");
        tvCur.setText(meterInfo.cur + "A");
        tvPower.setText(meterInfo.power + "W");
        tvFactory.setText(meterInfo.powerFactory + "");

//        tvAddr.setText(meterInfo.addrStr);
        updateChart();


    }


    private void initChart() {
        lineChart.getDescription().setEnabled(false);//设置描述
        lineChart.setPinchZoom(true);//设置按比例放缩柱状图
        lineChart.setExtraBottomOffset(20);
        lineChart.setExtraTopOffset(0);
        lineChart.setTouchEnabled(true);
        lineChart.setDragEnabled(true);
        lineChart.setScaleEnabled(true);


        //x坐标轴设置
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawLabels(true);
        xAxis.setGranularity(0.01f);
        xAxis.setLabelCount(7, false);
        xAxis.setCenterAxisLabels(true);//设置标签居中
        xAxis.setLabelRotationAngle(75);   // 标签倾斜

        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if (labelSize == 12) {
                    return Util.getMonthBefore()[(int) value];
                } else {

                    return Util.getDayBefore(labelSize)[(int) value];
                }
            }
        });

        //y轴设置
        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setDrawGridLines(false);
        leftAxis.setDrawLabels(true);
        leftAxis.setDrawAxisLine(true);
        leftAxis.setGranularity(0.01f);

        lineChart.getAxisRight().setEnabled(false);


        //图例设置
        Legend legend = lineChart.getLegend();
        legend.setEnabled(false);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
//        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(true);
        legend.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT);
        legend.setForm(Legend.LegendForm.SQUARE);
        legend.setTextSize(12f);

        //设置柱状图数据

        lineChart.animateY(1500);//数据显示动画，从左往右依次显示
//        lineChart.invalidate();
    }


    public void updateChart() {
        ArrayList<Entry> arrayList = new ArrayList<>();
        switch (currentClick) {
            case days_7:
                arrayList = meterInfo.getDayFreeze(7);
                labelSize = 7;
                break;
            case days_30:
                arrayList = meterInfo.getDayFreeze(30);
                labelSize = 30;
                break;
            case month_12:
                arrayList = meterInfo.getMonthFreeze();
                labelSize = 12;
                break;

        }

        LineDataSet dataSet = new LineDataSet(arrayList, "电量"); // add entries to dataset
//        dataSet.setColor(...);
//        dataSet.setValueTextColor(...); // styling, ...
        //x坐标轴设置


        lineChart.setData(new LineData(dataSet));
        XAxis xAxis = lineChart.getXAxis();
//
//        if (labelSize == 12) {
//            Util.getMonthBefore()[0];
//            xAxis.setAxisMinimum(a)
//
//        } else {
//            xAxis.setAxisMinimum(Util.getDayBefore(labelSize)[0]);
//
//            return ;
//        }

        xAxis.setLabelCount(labelSize, true);

        lineChart.invalidate();
    }


    private void addListener() {

        btn7Day.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                currentClick = CurrentClick.days_7;
                updateChart();

            }
        });
        btn31Day.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

//                byte[] data=Codec.readMeterInfo(meterInfo, Util.readType.readDayFreeze);
//                sendJson("meter_info", data);

                currentClick = CurrentClick.days_30;

                updateChart();


            }
        });
        btn12Month.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                byte[] data=Codec.readMeterInfo(meterInfo, Util.readType.readMonthFreeze);
//                sendJson("meter_info", data);

                currentClick = CurrentClick.month_12;
                updateChart();
            }
        });

        btnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (meterInfo.type == Util.TYPE_SINGLE_METER || meterInfo.type == Util.TYPE_MUTIL_METER) {

                    byte[] data = Codec.readMeterInfo(meterInfo, Util.readType.readRealData);


                    sendJson("meter_info", data);
                } else {
                    byte[] data = Codec.readMeterInfo(meterInfo, Util.readType.readCuurentData);
                    MyLog.d("sendMeterInfo===>" + Util.bcd2Str(data));

                    sendJson("meter_info", data);
                }
            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (meterInfo.type == Util.TYPE_SINGLE_METER || meterInfo.type == Util.TYPE_MUTIL_METER) {

                    byte[] data = Codec.readMeterInfo(meterInfo, Util.readType.readRealData);
//                    MyLog.d("sendMeterInfo===>" + Util.getBinaryStrFromByte(data));

                    sendJson("meter_info", data);
                } else {
                    byte[] data = Codec.readMeterInfo(meterInfo, Util.readType.readCuurentData);
//                    MyLog.d("sendMeterInfo===>" + Util.bcd2Str(data));

                    sendJson("meter_info", data);
                }
//                swipeRefreshLayout.stopNestedScroll();
            }
        });
    }


    private enum handler_key {

        /**
         * 更新界面
         */
        UPDATE_UI,

        DISCONNECT,
    }


    /**
     * The handler.
     */
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            handler_key key = handler_key.values()[msg.what];
            switch (key) {
                case UPDATE_UI:
                    updateUI();
                    break;
                case DISCONNECT:
//                    toastDeviceDisconnectAndExit();
                    break;
            }
        }
    };

    private void updateUI() {
        updateUi();
        swipeRefreshLayout.setRefreshing(false);

    }


    /*
      * 设备上报数据回调，此回调包括设备主动上报数据、下发控制命令成功后设备返回ACK
      */
    @Override
    protected void didReceiveData(GizWifiErrorCode result, GizWifiDevice device,
                                  ConcurrentHashMap<String, Object> dataMap, int sn) {
        super.didReceiveData(result, device, dataMap, sn);
        Log.i("liang555666", "接收到数据");
        if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS && dataMap.get("data") != null) {
            getDataFromReceiveDataMap(dataMap);
            mHandler.sendEmptyMessage(handler_key.UPDATE_UI.ordinal());
        }
    }

}
